<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2020/10/12
 * Time: 4:06 PM
 */
namespace app\index\logic;

use app\model\Goods;
use app\model\GoodsExchange;
use app\model\IntegralLog;
use app\model\User;
use think\facade\Db;
use think\facade\Request;

class ExchangeLogic
{

    public function getList()
    {
        $where = [
            'ge_orgid' => config('user')['orgid'],
            'ge_uid' => config('user')['id'],
        ];
        $goodsExchangeModel = new GoodsExchange();

        return $goodsExchangeModel->getGoodsExchangeListByCondition($where);
    }

    public function exchange($goodsId)
    {
        $goodsModel = new Goods();
        $goodsInfo = $goodsModel->getGoodsInfoById($goodsId);

        if(!$goodsInfo) fail('商品不存在');

        $integral = config('user')['integral'];
        //判断积分
        if($integral < $goodsInfo['exchangeIntegral'])  fail('账户积分不足');
        if($goodsInfo['stock'] == 0)  fail('库存不足，暂时不能兑换');

        //可以兑换
        Db::startTrans();
        try
        {
            //添加兑换记录
            $exchange = [
                'ge_orgid' => config('user')['orgid'],
                'ge_uid' => config('user')['id'],
                'ge_pername' => config('user')['pername'],
                'ge_goods_id' => $goodsId,
                'ge_goods_name' => $goodsInfo['name'],
            ];
            $exModel = new GoodsExchange();
            $exRet = $exModel->addOneExchange($exchange);
            if(!$exRet){
                Db::rollback();
                fail('兑换记录添加失败，请稍后重试');
            }
            $integralLog = [
                'integral_uid' => config('user')['id'],
                'integral_type' => IntegralLog::GOODS_EXCHANGE,
                'integral_way' => $exRet,
                'integral_num' => 0 - $goodsInfo['exchangeIntegral'],
                'integral_remark' => '使用积分兑换了'.$goodsInfo['name']
            ];
            //添加积分日志
            $integralLogModel = new IntegralLog();
            $rt = $integralLogModel->addLog($integralLog);
            if(!$rt){
                Db::rollback();
                fail('积分扣除失败，请稍后重试');
            }
            //更新积分
            $update = User::reduceUserIntegral(config('user')['id'],$goodsInfo['exchangeIntegral']);
            if(!$update){
                Db::rollback();
                fail('账户积分扣除失败，请稍后重试');
            }
            //商品库存减少
            $update = Goods::reduceStock($goodsId);
            if(!$update){
                Db::rollback();
                fail('库存更新失败，请稍后重试');
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
        }

        return true;
    }

}